import type { ref } from "vue";
import { type pieceoption, type outcome } from "./type"
export class Piece {
  //棋子的直径
  private d: number = 30
  public x: number
  public y: number
  public type: string
  public dom!: HTMLDivElement;
  constructor(option: pieceoption) {
    this.x = option.x
    this.y = option.y
    this.type = option.type
    this.playChess(option)
  }
  //初始化棋子
  private playChess(option: pieceoption): void {
    console.log('下了', option);
    const box = document.createElement('div')
    box.style.border = '1px solid' + option.type == 'h' ? 'black' : 'white'
    box.style.borderRadius = '50%'
    box.style.width = this.d + 'px'
    box.style.height = this.d + 'px'
    box.style.backgroundColor = option.type == 'h' ? 'black' : 'white'
    option.dom.appendChild(box)
    this.dom = box
  }
  //判断胜负
  public outCome(option: pieceoption, pieces: (Piece | null)[]): outcome {
    const pieceOutcome: outcome = {
      type: 'h',
      outcome: false,
      dom: null
    }
    let x: Piece[] = []
    let y: Piece[] = []
    let p: Piece[] = []
    let r: Piece[] = []
    pieces.forEach((item, index) => {
      //判断 一 方向的棋子是否到达5个
      if (option.x - 5 < item?.x! && item?.x! < option.x + 5 && option.y == item?.y && option.type == item?.type) {

        x.push(item)
        console.log('x:', x);
      }
      //判断 | 轴方向的棋子是否到达5个
      if (option.y - 5 < item?.y! && item?.y! < option.y + 5 && option.x == item?.x && option.type == item?.type) {
        y.push(item)
        console.log('y:', y);
      }
      //判断\方向的棋子是否到达5个
      if (-item?.y! - item?.x! == -option.y - option.x && option.x - 5 < item?.x! && item?.x! < option.x + 5 && option.type == item?.type) {
        r.push(item)
        console.log('r:', r);
      }
      //判断/方向的棋子是否到达5个
      if (-item?.y! + item?.x! == -option.y + option.x && option.x - 5 < item?.x! && item?.x! < option.x + 5 && option.type == item?.type) {
        p.push(item)
        console.log('p:', p);

      }

    })

    //胜利的情况
    if (x.length >= 5 && this.__checkArray(x, 'x') || y.length >= 5 && this.__checkArray(y, 'y') || p.length >= 5 && this.__checkArray(p, 'y') || r.length >= 5 && this.__checkArray(r, 'y')) {

      pieceOutcome.outcome = true
      pieceOutcome.type = option.type
    }
    pieceOutcome.dom = this.dom
    return pieceOutcome
  }
  //判断是否有五个相同颜色的棋子连接一起
  private __checkArray(array: any, l: string) {
    return array[3][l] + array[1][l] == array[2][l] * 2
  }
}
